package com.ytzl.itrip.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytzl.itrip.auth.service.ItripUserService;
import com.ytzl.itrip.beans.model.ItripUser;
import com.ytzl.itrip.utils.common.*;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2018/7/10.
 */
@Controller
@RequestMapping("/api")
public class ItripUserController {

    @Resource
    private ItripUserService itripUserService;
    @Resource
    private RedisAPI redisAPI;
    @Resource
    private SendTemSMS sendTemSMS;
    @Resource
    private SendMail sendMail;

    @RequestMapping(value = "/dologin",
            method = RequestMethod.POST,
            produces = "application/json")
    @ResponseBody
    public Dto<DtoVo> dologin(@Param("name") String name,
                              @Param("password") String password,
                              HttpServletRequest request,
                              HttpServletResponse response,
                              HttpSession session) throws Exception {
        ItripUser itripUser = null;
        itripUser=itripUserService.findByCode(name);
        if (itripUser!=null){
            Boolean b = DigestUtil.hmacSign(password,"yuntuzhilian").equals(itripUser.getUserPassword());
            if (b){
                if (itripUser.getActivated()!=null){
                   if (itripUser.getActivated()==1){
                       // 第一次发送请求时间
                       Long time = Calendar.getInstance().getTimeInMillis();
                       String token = "PC:"+
                               "_"+DigestUtil.hmacSign(name,"yuntuzhilian")+
                               "_"+time+
                               "_"+itripUser.getId()+
                               "_"+ DigestUtils.md5DigestAsHex(request.getHeader("user-agent").getBytes()).substring(0,6);
                       String gentime="60*60*2*1000";
                       DtoVo dtoVo = new DtoVo(time+gentime,gentime,token,
                               DtoUtil.returnSuccess("登录成功",itripUser));
                       redisAPI.set("token:["+itripUser.getUserCode()+"]",token,60*60*2*1000);
                       redisAPI.set(token, JSON.toJSONString(itripUser));
                       response.setHeader("token",token);
                       session.setAttribute("USER",itripUser);
                       return DtoUtil.returnDataSuccess(dtoVo);
                   }
                }else{
                    return DtoUtil.returnFail("用户未激活","30003");
                }
            }else{
                return DtoUtil.returnFail("密码错误","30002");
            }
        }
        return DtoUtil.returnFail("登录失败,用户不存在","30001");
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public Dto<ItripUser> logout(HttpServletRequest request,
            HttpSession session){
        String token = request.getHeader("token");
        if (redisAPI.get(token)!=null){
            session.removeAttribute("USER");
        }
        return DtoUtil.returnSuccess("logout success",null);
    }

    @RequestMapping(value = "/ckusr",method = RequestMethod.GET)
    @ResponseBody
    public Object ckuser(@RequestParam("name") String name) throws Exception {
        Map map = new HashMap();
        map.put("userCode",name);
        List<ItripUser> list =itripUserService.getListByMap(map);
        if (list.size()>0){
            return DtoUtil.returnFail("该邮箱已被注册","6001");
        }
        return DtoUtil.returnSuccess("邮箱未注册");
    }

    @RequestMapping("registerbyphone")
    @ResponseBody
    public Object registerbyphone(@RequestBody JSONObject object) throws Exception {
        ItripUser itripUser = new ItripUser();
        String data = object.toJSONString();
        JSONObject json = JSON.parseObject(data);
        itripUser.setUserCode(json.getString("userCode"));
        itripUser.setUserName(json.getString("userName"));
        itripUser.setUserPassword(DigestUtil.hmacSign(json.getString("userPassword"),"yuntuzhilian") );
        itripUserService.save(itripUser);
        sendTemSMS.sendSMS(itripUser.getUserCode(),"1","3");
        return DtoUtil.returnSuccess("注册成功",itripUser);
    }

    @RequestMapping(value = "/validatephone",method = RequestMethod.PUT)
    @ResponseBody
    public Object validatephone(@RequestParam("user")
                                @ApiParam(value = "用户账号",required = true) String user,
                                @RequestParam("code")
                                 @ApiParam(value = "激活码",required = true) String code) throws Exception {
        String codeId = redisAPI.get("activation:["+user+"]");
        if (codeId!=null && code.equals(codeId)){
            Long id = itripUserService.findByCode(user).getId();
            if (id!=null){
                ItripUser itripUser = new ItripUser();
                itripUser.setId(id);
                itripUser.setActivated(1);
                itripUserService.modify(itripUser);
            }
            return DtoUtil.returnSuccess("用户激活成功");
        }
        return DtoUtil.returnFail("激活失败","6002");
    }

    @RequestMapping(value = "doregister",method = RequestMethod.POST)
    @ResponseBody
    public Object doregister(@RequestBody JSONObject object) throws Exception {
        ItripUser itripUser = new ItripUser();
        String data = object.toJSONString();
        JSONObject json = JSON.parseObject(data);
        itripUser.setUserCode(json.getString("userCode"));
        itripUser.setUserName(json.getString("userName"));
        itripUser.setUserPassword(DigestUtil.hmacSign(json.getString("userPassword"),"yuntuzhilian"));
        sendMail.send(json.getString("userCode"));
        itripUserService.save(itripUser);
        return DtoUtil.returnSuccess("注册成功",itripUser);
    }

    @RequestMapping(value = "/activate",method = RequestMethod.PUT)
    @ResponseBody
    public Object activate(@RequestParam("user") String user,
                           @RequestParam("code") String code) throws Exception {
        String mailCode = redisAPI.get("mailCode:["+user+"]");
        ItripUser itripUsers = itripUserService.findByCode(user);
        System.out.println(itripUsers.getId());
        if (itripUsers!=null){
            if (mailCode!=null && code.equals(mailCode)){
                    ItripUser itripUser = new ItripUser();
                    itripUser.setActivated(1);
                    itripUser.setId(itripUsers.getId());
                    itripUserService.modify(itripUser);
                return DtoUtil.returnSuccess("激活成功");
            }else{
                return DtoUtil.returnFail("验证码错误","2002");
            }
        }else{
            return DtoUtil.returnFail("邮箱或手机号未注册","2001");
        }
    }

}
